package com.eques.demo

import android.os.Bundle
import android.widget.TextView
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.eques.base.BaseActivity
import com.eques.bean.LockMessage
import com.eques.demo.adapter.LockMessageAdapter
import com.eques.util.Config
import com.eques.util.DateTimeUtil
import com.eques.util.HttpUtil
import org.json.JSONObject

class LockMessageListActivity : BaseActivity() {

    private lateinit var recyclerView: RecyclerView
    private lateinit var adapter: LockMessageAdapter
    private lateinit var tvEmpty: TextView
    private lateinit var tvTotal: TextView
    private lateinit var tvUnreadCount: TextView
    private var devId: String = ""

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_lock_message_list)
        devId = intent.getStringExtra("devId").toString()
        initView()
    }

    override fun initView() {
        initViews()
        setupRecyclerView()
        loadData()
    }

    override fun initData() {
    }

    private fun initViews() {
        recyclerView = findViewById(R.id.recyclerView)
        tvEmpty = findViewById(R.id.tv_empty)
        tvTotal = findViewById(R.id.tv_total)
        tvUnreadCount = findViewById(R.id.tv_unread_count)

        // 设置标题
        findViewById<TextView>(R.id.tv_title).text = "锁消息"
    }

    private fun setupRecyclerView() {
        adapter = LockMessageAdapter()
        recyclerView.layoutManager = LinearLayoutManager(this)
        recyclerView.adapter = adapter

        // 设置点击监听
        adapter.onItemClickListener = { message ->
            showMessageDetail(message)
            // 标记为已读
            markAsRead(message)
        }
    }

    private fun loadData() {
        var startAndEndDate = DateTimeUtil.getCurrDate()
        var startTime = java.lang.String.valueOf(
            DateTimeUtil.getSpecifiedDateTime_000000(startAndEndDate).time
        )
        var endTime = java.lang.String.valueOf(
            DateTimeUtil.getSpecifiedDateTime_235959(startAndEndDate).time
        )
        val host = preference.getSubUrl()
        val token = preference.getString(Config.EQUES_USER_TOKEN)
        val uid = preference.getString(Config.EQUES_USER_UID)
        val url = Config.getE1ProOpenLockRecordListUrl(
            host,
            uid,
            token,
            devId,
            startTime,
            endTime,
            "0",
            "1000"
        )
        println("GET LockMsg url: $url")
        HttpUtil.getAsync(
            url = url.toString(),
        ) { result ->
            result.onSuccess { response ->
                println("GET Alarm Response: $response")
                runOnUiThread {
                    parseAndDisplayData(response)
                }

            }.onFailure { exception ->
                println("GET Error: ${exception.message}")
            }
        }


    }

    private fun parseAndDisplayData(jsonString: String) {
        try {
            val jsonObject = JSONObject(jsonString)
            val listArray = jsonObject.getJSONArray("list")
            val total = jsonObject.getInt("total")
            val messages = mutableListOf<LockMessage>()

            for (i in 0 until listArray.length()) {
                val item = listArray.getJSONObject(i)
                val message = LockMessage(
                    record_id = item.getString("record_id"),
                    identifier = item.getString("identifier"),
                    create_time = item.getLong("create_time"),
                    lock_detail_id = item.getString("lock_detail_id"),
                    time = item.getLong("time"),
                    state = item.getInt("state"),
                    msg_id = item.getString("msg_id"),
                    type = item.getInt("type"),
                    lock_id = item.getString("lock_id")
                )
                messages.add(message)
            }

            adapter.setData(messages)

            // 显示统计信息
            updateStatistics(messages, total)

        } catch (e: Exception) {
            e.printStackTrace()
            tvEmpty.text = "数据加载失败"
            tvEmpty.visibility = TextView.VISIBLE
            recyclerView.visibility = RecyclerView.GONE
            tvTotal.visibility = TextView.GONE
            tvUnreadCount.visibility = TextView.GONE
        }
    }

    private fun updateStatistics(messages: List<LockMessage>, total: Int) {
        val unreadCount = messages.count { it.isUnread() }

        tvTotal.text = "共 $total 条消息"
        tvUnreadCount.text = "未读: $unreadCount"

        // 显示/隐藏空状态
        if (messages.isEmpty()) {
            tvEmpty.visibility = TextView.VISIBLE
            recyclerView.visibility = RecyclerView.GONE
            tvTotal.visibility = TextView.GONE
            tvUnreadCount.visibility = TextView.GONE
        } else {
            tvEmpty.visibility = TextView.GONE
            recyclerView.visibility = RecyclerView.VISIBLE
            tvTotal.visibility = TextView.VISIBLE
            tvUnreadCount.visibility = TextView.GONE
        }
    }

    private fun showMessageDetail(message: LockMessage) {
        // 显示消息详情
        android.widget.Toast.makeText(
            this,
            "${message.getMessageType()}\n时间: ${message.getDetailTime()}\n消息ID: ${message.msg_id}",
            android.widget.Toast.LENGTH_LONG
        ).show()
    }

    private fun markAsRead(message: LockMessage) {
        // 这里实现标记为已读的逻辑
        // 可以更新本地数据库或调用API接口
        // 然后刷新列表
    }
}